/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sciStudio.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.Msg.domain.Msg;
import com.fzhucc.modules.Msg.domain.dto.SmallMsgDto;
import com.fzhucc.modules.Msg.repository.MsgRepository;
import com.fzhucc.modules.modelDemand.domain.ModelDemandAuditLog;
import com.fzhucc.modules.modelDemand.repository.ModelDemandAuditLogRepository;
import com.fzhucc.modules.sciCxResult.domain.SciCxResult;
import com.fzhucc.modules.sciCxResult.domain.SciCxResultInfo;
import com.fzhucc.modules.sciCxResult.domain.dto.SciCxResultDto;
import com.fzhucc.modules.sciCxResult.repository.SciCxResultInfoRepository;
import com.fzhucc.modules.sciCxResult.repository.SciCxResultRepository;
import com.fzhucc.modules.sciCxResult.service.mapstruct.SciCxResultInfoMapper;
import com.fzhucc.modules.sciCxResult.service.mapstruct.SciCxResultMapper;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoLesson;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoResult;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoWe;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoDto;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoLessonRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoResultRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoWeRepository;
import com.fzhucc.modules.sciPersonnelInfo.service.mapstruct.SciPersonnelInfoMapper;
import com.fzhucc.modules.sciStudio.domain.SciStudio;
import com.fzhucc.modules.sciStudio.domain.SciStudioImg;
import com.fzhucc.modules.sciStudio.domain.SciStudioInfo;
import com.fzhucc.modules.sciStudio.domain.dto.*;
import com.fzhucc.modules.sciStudio.repository.SciStudioImgRepository;
import com.fzhucc.modules.sciStudio.repository.SciStudioInfoRepository;
import com.fzhucc.modules.sciStudio.service.mapstruct.SciStudioImgMapper;
import com.fzhucc.modules.sciStudio.service.mapstruct.SciStudioInfoMapper;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemandInfo;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.*;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.domain.UserSmall;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.repository.UserSmallRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciStudio.repository.SciStudioRepository;
import com.fzhucc.modules.sciStudio.service.mapstruct.SciStudioMapper;
import org.hibernate.loader.entity.NaturalIdEntityJoinWalker;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-01-10
 **/
@Service
@RequiredArgsConstructor
public class SciStudioService {

    private final SciStudioRepository sciStudioRepository;

    private final MsgRepository msgRepository;

    private final UserSmallRepository userSmallRepository;

    private final SciPersonnelInfoRepository sciPersonnelInfoRepository;

    private final SciPersonnelInfoMapper sciPersonnelInfoMapper;

    private final ModelDemandAuditLogRepository modelDemandAuditLogRepository;

    private final SciStudioInfoRepository sciStudioInfoRepository;

    private final SciStudioImgRepository sciStudioImgRepository;
    private final SciStudioMapper sciStudioMapper;

    private final SciCxResultMapper sciCxResultMapper;

    private final SciStudioImgMapper sciStudioImgMapper;

    private final SciStudioInfoMapper sciStudioInfoMapper;

    private final UserRepository userRepository;

    private final SciCxResultRepository sciCxResultRepository;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final SciCxResultInfoMapper sciCxResultInfoMapper;

    private final SciCxResultInfoRepository sciCxResultInfoRepository;

    private final SciPersonnelInfoResultRepository sciPersonnelInfoResultRepository;

    private final SciPersonnelInfoWeRepository sciPersonnelInfoWeRepository;

    private final SciPersonnelInfoLessonRepository sciPersonnelInfoLessonRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${sci.audit.qxdsh}")
    public String qxdsh;

    @Value("${sci.audit.sjdsh}")
    public String sjdsh;

    @Value("${sci.audit.shtg}")
    public String shtg;

    @Value("${sci.log.model}")
    public String model;

    @Value("${sci.audit.bh}")
    public String bh;

    @Value("${sci.doStatus}")
    public String ppz;

    @Value("${sci.doStatusypp}")
    public String ypp;

    @Value("${sci.doStatusyjj}")
    public String yjj;

    @Value("${sci.log.gzs}")
    public String gzs;

    @Value("${sci.stage.quPass}")
    public String quPass;

    @Value("${sci.stage.quNoPass}")
    public String quNoPass;

    @Value("${sci.stage.cityPass}")
    public String cityPass;

    @Value("${sci.stage.cityNoPass}")
    public String cityNoPass;

    @Value("${sci.log.cxcg}")
    public String cxcg;


    public Map<String, Object> my(SciStudioQueryCriteria criteria, Pageable pageable) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        Page<SciStudio> page = sciStudioRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciStudioDto> map = page.map(sciStudioMapper::toDto);
        List<SciStudioDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciStudioDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }
                String type = dto.getType();
                if (type != null && type.contains(";")) {
                    String[] array = type.split(";");
                    dto.setTypes(array);
                } else {
                    String[] array = {};
                    dto.setTypes(array);
                }

                List<SciStudioInfo> lists = sciStudioInfoRepository.findByStId(dto.getId());
                dto.setListSciStudioInfo(sciStudioInfoMapper.toDto(lists));

                List<SciStudioImg> lists2 = sciStudioImgRepository.findByStId(dto.getId());
                List<SciStudioImgDto> sciStudioImgDtos = sciStudioImgMapper.toDto(lists2);
                List<String> imgs = new ArrayList<String>();
                if (sciStudioImgDtos != null && sciStudioImgDtos.size() > 0) {
                    for (SciStudioImgDto dto2 : sciStudioImgDtos) {
                        imgs.add(dto2.getPic());
                    }
                }
                dto.setListSciStudioImg(imgs);

                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), gzs);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                if (dto.getModelId() != null) {
                    //TODO 把劳模信息也返回
                    Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(dto.getModelId());
                    if (ops.isPresent()) {
                        //劳模信息
                        SciPersonnelInfo sciPersonnelInfo = ops.get();
                        SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(sciPersonnelInfo);
                        String matype = sciPersonnelInfoDto.getMatype();
                        if (matype != null && matype.contains(";")) {
                            String[] array = matype.split(";");
                            sciPersonnelInfoDto.setMatypes(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setMatypes(array);
                        }
                        String retype = sciPersonnelInfoDto.getRetype();
                        if (retype != null && retype.contains(";")) {
                            String[] array = retype.split(";");
                            sciPersonnelInfoDto.setRetypes(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setRetypes(array);
                        }
                        String keyword = sciPersonnelInfoDto.getKeyword();
                        if (keyword != null && keyword.contains(";")) {
                            String[] array = keyword.split(";");
                            sciPersonnelInfoDto.setKeywords(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setKeywords(array);
                        }
                        String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                        if (orgArea2 != null && orgArea2.contains(";")) {
                            String[] array = orgArea2.split(";");
                            sciPersonnelInfoDto.setOrgAreas(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setOrgAreas(array);
                        }
                        Integer id = sciPersonnelInfoDto.getId();
                        List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListResult(results);
                        List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListLesson(list2);
                        List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListWe(list3);
                        List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(id, model);
                        sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs2);
                        dto.setSciPersonnelInfoDto(sciPersonnelInfoDto);
                    }
                }


                List<SciCxResult> list3 = sciCxResultRepository.findByStudioId(dto.getId());
                if (list3 != null) {
                    List<SciCxResultDto> sciCxResultDtos = sciCxResultMapper.toDto(list3);
                    if (sciCxResultDtos != null && sciCxResultDtos.size() > 0) {
                        for (SciCxResultDto dto2 : sciCxResultDtos) {
                            String orgArea2 = dto2.getOrgArea();
                            if (orgArea2 != null && orgArea2.contains(";")) {
                                String[] array = orgArea2.split(";");
                                dto2.setOrgAreas(array);
                            } else {
                                String[] array = {};
                                dto2.setOrgAreas(array);
                            }
                            List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(dto2.getId(), cxcg);
                            dto2.setListModelDemandAuditLog(modelDemandAuditLogs2);
                            List<SciCxResultInfo> lists5 = sciCxResultInfoRepository.findByCxId(dto2.getId());
                            dto2.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists5));
                        }
                    }
                    dto.setListCxcg(sciCxResultDtos);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAll(SciStudioQueryCriteria criteria, Pageable pageable) {
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        criteria.setIsDelete(0);
        criteria.setOrgAreas(null);
        Page<SciStudio> page = sciStudioRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciStudioDto> map = page.map(sciStudioMapper::toDto);
        List<SciStudioDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciStudioDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                String type = dto.getType();
                if (type != null && type.contains(";")) {
                    String[] array = type.split(";");
                    dto.setTypes(array);
                } else {
                    String[] array = {};
                    dto.setTypes(array);
                }

                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), gzs);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                List<SciStudioInfo> lists = sciStudioInfoRepository.findByStId(dto.getId());
                dto.setListSciStudioInfo(sciStudioInfoMapper.toDto(lists));

                List<SciStudioImg> lists2 = sciStudioImgRepository.findByStId(dto.getId());
                List<String> imgs = new ArrayList<String>();
                if (lists2 != null && lists2.size() > 0) {
                    for (SciStudioImg dto2 : lists2) {
                        imgs.add(dto2.getPic());
                    }
                }
                dto.setListSciStudioImg(imgs);

                if (dto.getModelId() != null) {
                    //TODO 把劳模信息也返回
                    Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(dto.getModelId());
                    if (ops.isPresent()) {
                        //劳模信息
                        SciPersonnelInfo sciPersonnelInfo = ops.get();
                        SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(sciPersonnelInfo);
                        String matype = sciPersonnelInfoDto.getMatype();
                        if (matype != null && matype.contains(";")) {
                            String[] array = matype.split(";");
                            sciPersonnelInfoDto.setMatypes(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setMatypes(array);
                        }
                        String retype = sciPersonnelInfoDto.getRetype();
                        if (retype != null && retype.contains(";")) {
                            String[] array = retype.split(";");
                            sciPersonnelInfoDto.setRetypes(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setRetypes(array);
                        }
                        String keyword = sciPersonnelInfoDto.getKeyword();
                        if (keyword != null && keyword.contains(";")) {
                            String[] array = keyword.split(";");
                            sciPersonnelInfoDto.setKeywords(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setKeywords(array);
                        }
                        String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                        if (orgArea2 != null && orgArea2.contains(";")) {
                            String[] array = orgArea2.split(";");
                            sciPersonnelInfoDto.setOrgAreas(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setOrgAreas(array);
                        }
                        Integer id = sciPersonnelInfoDto.getId();
                        List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListResult(results);
                        List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListLesson(list2);
                        List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListWe(list3);
                        List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(id, model);
                        sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs2);
                        dto.setSciPersonnelInfoDto(sciPersonnelInfoDto);
                    }
                }

                List<SciCxResult> list3 = sciCxResultRepository.findByStudioId(dto.getId());
                if (list3 != null) {
                    List<SciCxResultDto> sciCxResultDtos = sciCxResultMapper.toDto(list3);
                    if (sciCxResultDtos != null && sciCxResultDtos.size() > 0) {
                        for (SciCxResultDto dto2 : sciCxResultDtos) {
                            String orgArea2 = dto2.getOrgArea();
                            if (orgArea2 != null && orgArea2.contains(";")) {
                                String[] array = orgArea2.split(";");
                                dto2.setOrgAreas(array);
                            } else {
                                String[] array = {};
                                dto2.setOrgAreas(array);
                            }
                            List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(dto2.getId(), cxcg);
                            dto2.setListModelDemandAuditLog(modelDemandAuditLogs2);
                            List<SciCxResultInfo> lists5 = sciCxResultInfoRepository.findByCxId(dto2.getId());
                            dto2.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists5));
                        }
                    }
                    dto.setListCxcg(sciCxResultDtos);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAllh5(SciStudioQueryCriteria criteria, Pageable pageable) {
        criteria.setIsDelete(0);
        if (criteria.getOrgArea() != null && criteria.getOrgArea().equals(all)) {
            //h5的直接传orgArea
            criteria.setOrgArea(null);
        }
        Page<SciStudio> page = sciStudioRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciStudioDto> map = page.map(sciStudioMapper::toDto);
        List<SciStudioDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciStudioDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                String type = dto.getType();
                if (type != null && type.contains(";")) {
                    String[] array = type.split(";");
                    dto.setTypes(array);
                } else {
                    String[] array = {};
                    dto.setTypes(array);
                }

                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), gzs);
                dto.setListModelDemandAuditLog(modelDemandAuditLogs);

                List<SciStudioInfo> lists = sciStudioInfoRepository.findByStId(dto.getId());
                dto.setListSciStudioInfo(sciStudioInfoMapper.toDto(lists));

                List<SciStudioImg> lists2 = sciStudioImgRepository.findByStId(dto.getId());
                List<String> imgs = new ArrayList<String>();
                if (lists2 != null && lists2.size() > 0) {
                    for (SciStudioImg dto2 : lists2) {
                        imgs.add(dto2.getPic());
                    }
                }
                dto.setListSciStudioImg(imgs);

                if (dto.getModelId() != null) {
                    //TODO 把劳模信息也返回
                    Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(dto.getModelId());
                    if (ops.isPresent()) {
                        //劳模信息
                        SciPersonnelInfo sciPersonnelInfo = ops.get();
                        SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(sciPersonnelInfo);
                        String matype = sciPersonnelInfoDto.getMatype();
                        if (matype != null && matype.contains(";")) {
                            String[] array = matype.split(";");
                            sciPersonnelInfoDto.setMatypes(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setMatypes(array);
                        }
                        String retype = sciPersonnelInfoDto.getRetype();
                        if (retype != null && retype.contains(";")) {
                            String[] array = retype.split(";");
                            sciPersonnelInfoDto.setRetypes(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setRetypes(array);
                        }
                        String keyword = sciPersonnelInfoDto.getKeyword();
                        if (keyword != null && keyword.contains(";")) {
                            String[] array = keyword.split(";");
                            sciPersonnelInfoDto.setKeywords(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setKeywords(array);
                        }
                        String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                        if (orgArea2 != null && orgArea2.contains(";")) {
                            String[] array = orgArea2.split(";");
                            sciPersonnelInfoDto.setOrgAreas(array);
                        } else {
                            String[] array = {};
                            sciPersonnelInfoDto.setOrgAreas(array);
                        }
                        Integer id = sciPersonnelInfoDto.getId();
                        List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListResult(results);
                        List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListLesson(list2);
                        List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                        sciPersonnelInfoDto.setListWe(list3);
                        List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(id, model);
                        sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs2);
                        dto.setSciPersonnelInfoDto(sciPersonnelInfoDto);
                    }
                }

                List<SciCxResult> list3 = sciCxResultRepository.findByStudioId(dto.getId());
                if (list3 != null) {
                    List<SciCxResultDto> sciCxResultDtos = sciCxResultMapper.toDto(list3);
                    if (sciCxResultDtos != null && sciCxResultDtos.size() > 0) {
                        for (SciCxResultDto dto2 : sciCxResultDtos) {
                            String orgArea2 = dto2.getOrgArea();
                            if (orgArea2 != null && orgArea2.contains(";")) {
                                String[] array = orgArea2.split(";");
                                dto2.setOrgAreas(array);
                            } else {
                                String[] array = {};
                                dto2.setOrgAreas(array);
                            }
                            List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(dto2.getId(), cxcg);
                            dto2.setListModelDemandAuditLog(modelDemandAuditLogs2);
                            List<SciCxResultInfo> lists5 = sciCxResultInfoRepository.findByCxId(dto2.getId());
                            dto2.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists5));
                        }
                    }
                    dto.setListCxcg(sciCxResultDtos);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看
    public String setCriteria(SciStudioQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && (orgArea.equals(all) || orgArea.equals(all2))) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public List<SciStudioDto> queryAll(SciStudioQueryCriteria criteria) {
        //导出  如果有传则按传的数组 导出
        criteria.setIsDelete(0);
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        return sciStudioMapper.toDto(sciStudioRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public List<SciStudioDto> queryAllmy(SciStudioQueryCriteria criteria) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        return sciStudioMapper.toDto(sciStudioRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public SciStudioDto findById(Integer id) {
        SciStudio sciStudio = sciStudioRepository.findById(id).orElseGet(SciStudio::new);
        ValidationUtil.isNull(sciStudio.getId(), "SciStudio", "id", id);
        //查询热度 +1
        Integer hot = sciStudio.getHot();
        sciStudio.setHot(hot + 1);
        SciStudio save = sciStudioRepository.save(sciStudio);
        SciStudioDto dto = sciStudioMapper.toDto(save);

        String orgArea = dto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            dto.setOrgAreas(array);
        } else {
            String[] array = {};
            dto.setOrgAreas(array);
        }

        String type = dto.getType();
        if (type != null && type.contains(";")) {
            String[] array = type.split(";");
            dto.setTypes(array);
        } else {
            String[] array = {};
            dto.setTypes(array);
        }

        List<SciStudioInfo> lists = sciStudioInfoRepository.findByStId(dto.getId());
        dto.setListSciStudioInfo(sciStudioInfoMapper.toDto(lists));

        List<SciStudioImg> lists2 = sciStudioImgRepository.findByStId(dto.getId());
        List<String> imgs = new ArrayList<String>();
        if (lists2 != null && lists2.size() > 0) {
            for (SciStudioImg dto2 : lists2) {
                imgs.add(dto2.getPic());
            }
        }
        dto.setListSciStudioImg(imgs);

        List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(dto.getId(), gzs);
        dto.setListModelDemandAuditLog(modelDemandAuditLogs);

        if (dto.getModelId() != null) {
            //TODO 把劳模信息也返回
            Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(dto.getModelId());
            if (ops.isPresent()) {
                //劳模信息
                SciPersonnelInfo sciPersonnelInfo = ops.get();
                SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(sciPersonnelInfo);
                String matype = sciPersonnelInfoDto.getMatype();
                if (matype != null && matype.contains(";")) {
                    String[] array = matype.split(";");
                    sciPersonnelInfoDto.setMatypes(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setMatypes(array);
                }
                String retype = sciPersonnelInfoDto.getRetype();
                if (retype != null && retype.contains(";")) {
                    String[] array = retype.split(";");
                    sciPersonnelInfoDto.setRetypes(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setRetypes(array);
                }
                String keyword = sciPersonnelInfoDto.getKeyword();
                if (keyword != null && keyword.contains(";")) {
                    String[] array = keyword.split(";");
                    sciPersonnelInfoDto.setKeywords(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setKeywords(array);
                }
                String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                if (orgArea2 != null && orgArea2.contains(";")) {
                    String[] array = orgArea2.split(";");
                    sciPersonnelInfoDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setOrgAreas(array);
                }
                Integer myid = sciPersonnelInfoDto.getId();
                List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(myid);
                sciPersonnelInfoDto.setListResult(results);
                List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(myid);
                sciPersonnelInfoDto.setListLesson(list2);
                List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(myid);
                sciPersonnelInfoDto.setListWe(list3);
                List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(myid, model);
                sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs2);
                dto.setSciPersonnelInfoDto(sciPersonnelInfoDto);
            }
        }

        List<SciCxResult> list3 = sciCxResultRepository.findByStudioIdWithAuditStatus(dto.getId(), shtg);
        if (list3 != null) {
            List<SciCxResultDto> sciCxResultDtos = sciCxResultMapper.toDto(list3);
            if (sciCxResultDtos != null && sciCxResultDtos.size() > 0) {
                for (SciCxResultDto dto2 : sciCxResultDtos) {
                    String orgArea2 = dto2.getOrgArea();
                    if (orgArea2 != null && orgArea2.contains(";")) {
                        String[] array = orgArea2.split(";");
                        dto2.setOrgAreas(array);
                    } else {
                        String[] array = {};
                        dto2.setOrgAreas(array);
                    }
                    List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(dto2.getId(), cxcg);
                    dto2.setListModelDemandAuditLog(modelDemandAuditLogs2);
                    List<SciCxResultInfo> lists5 = sciCxResultInfoRepository.findByCxId(dto2.getId());
                    dto2.setListSciCxResultInfo(sciCxResultInfoMapper.toDto(lists5));
                }
            }
            dto.setListCxcg(sciCxResultDtos);
        }

        List<Msg> listMsg = msgRepository.findNormalByGlIdWithAuditStatus(dto.getId(), "审核通过", "%工作室%");
        if (listMsg != null && listMsg.size() > 0) {
            List<SmallMsgDto> myList = new ArrayList<SmallMsgDto>();
            for (Msg msg : listMsg) {
                SmallMsgDto smallMsgDto = new SmallMsgDto();
                smallMsgDto.setId(msg.getId());
                smallMsgDto.setGlId(msg.getGlId());
                smallMsgDto.setType(msg.getType());
                smallMsgDto.setContext(msg.getContext());
                smallMsgDto.setAuditStatus(msg.getAuditStatus());
                smallMsgDto.setUserId(msg.getUserId());
                smallMsgDto.setUpdateBy(msg.getUpdateBy());
                smallMsgDto.setCreateTime(msg.getCreateTime());
                smallMsgDto.setCreateBy(msg.getCreateBy());
                smallMsgDto.setUpdateTime(msg.getUpdateTime());
                Optional<UserSmall> res = userSmallRepository.findById(msg.getUserId());
                if (res.isPresent()) {
                    smallMsgDto.setUserSmall(res.get());
                }
                myList.add(smallMsgDto);
            }
            dto.setMsgDto(myList);
        }
        return dto;
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public SciStudioDto create(SciStudioAddDto dto) {
        String name = dto.getName();
        if (name == null) {
            throw new BadRequestException("工作室名称为空");
        }
        if (dto.getModelId() != null) {
            Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(dto.getModelId());
            if (!ops.isPresent()) {
                throw new BadRequestException("未找到劳模");
            }
        }

        SciStudio resources = new SciStudio();
        resources.setPic(dto.getPic());
        resources.setName(name);
        resources.setModelId(dto.getModelId());
        resources.setUnit(dto.getUnit());
        resources.setSzUnit(dto.getSzUnit());
        resources.setNum(dto.getNum());
        resources.setStudioCreateYear(dto.getStudioCreateYear());
        resources.setIsEdit(0);//设置默认添加不可编辑
        resources.setHot(0);
        resources.setMainWork(dto.getMainWork());
        resources.setContacts(dto.getContacts());
        resources.setContactsWay(dto.getContactsWay());
        resources.setLeaderName(dto.getLeaderName());
        resources.setLeaderSex(dto.getLeaderSex());
        resources.setLeaderBirth(dto.getLeaderBirth());
        resources.setLeaderPostUnit(dto.getLeaderPostUnit());
        resources.setLeaderHonor(dto.getLeaderHonor());
        resources.setLeaderAwardYear(dto.getLeaderAwardYear());
        resources.setDetails(dto.getDetails());
        resources.setBndYearExpenses(dto.getBndYearExpenses());
        resources.setSYearInCons(dto.getSYearInCons());
        resources.setSCxResult(dto.getSCxResult());
        resources.setSCxResultChange(dto.getSCxResultChange());
        resources.setSCxZlApplyCons(dto.getSCxZlApplyCons());
        resources.setSRcTrain(dto.getSRcTrain());
        resources.setSRcSkillLevel(dto.getSRcSkillLevel());
        resources.setSJjCsFee(dto.getSJjCsFee());
        resources.setSJjJyFee(dto.getSJjJyFee());
        resources.setSShxy(dto.getSShxy());
        resources.setIsDelete(0);
        resources.setUserId(SecurityUtils.getCurrentUserId());
        resources.setIsShow(0);
        resources.setSort(1);
        resources.setAuditStatus(qxdsh);//区县待审核
        if (dto.getTypes() != null && dto.getTypes().length > 0) {
            String last = "";
            for (String a : dto.getTypes()) {
                last = last + a + ";";
            }
            resources.setType(last);
        } else {
            resources.setType(null);
        }
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        SciStudioDto sciStudioDto = sciStudioMapper.toDto(sciStudioRepository.save(resources));

        //根据id设置sort
        Optional<SciStudio> result = sciStudioRepository.findById(sciStudioDto.getId());
        if (result.isPresent()) {
            SciStudio sciCxResult = result.get();
            sciCxResult.setSort(sciCxResult.getId());
            sciStudioRepository.save(sciCxResult);
        }

        List<String> listSciStudioImg = dto.getListSciStudioImg();
        if (listSciStudioImg != null && listSciStudioImg.size() > 0) {
            for (String res : listSciStudioImg) {
                SciStudioImg sciStudioImg = new SciStudioImg();
                sciStudioImg.setPic(res);
                sciStudioImg.setStId(sciStudioDto.getId());
                sciStudioImgRepository.save(sciStudioImg);
            }
        }
        List<SciStudioInfoAddDto> listSciStudioInfo = dto.getListSciStudioInfo();
        if (listSciStudioInfo != null && listSciStudioInfo.size() > 0) {
            for (SciStudioInfoAddDto res : listSciStudioInfo) {
                SciStudioInfo sciStudioInfo = new SciStudioInfo();
                sciStudioInfo.setName(res.getName());
                sciStudioInfo.setWork(res.getWork());
                sciStudioInfo.setTitle(res.getTitle());
                sciStudioInfo.setUnitPosition(res.getUnitPosition());
                sciStudioInfo.setStId(sciStudioDto.getId());
                sciStudioInfoRepository.save(sciStudioInfo);
            }
        }

        List<SciStudioInfo> list1 = sciStudioInfoRepository.findByStId(sciStudioDto.getId());
        sciStudioDto.setListSciStudioInfo(sciStudioInfoMapper.toDto(list1));

        List<SciStudioImg> list2 = sciStudioImgRepository.findByStId(sciStudioDto.getId());
        List<String> imgs = new ArrayList<String>();
        if (list2 != null && list2.size() > 0) {
            for (SciStudioImg dto2 : list2) {
                imgs.add(dto2.getPic());
            }
        }
        sciStudioDto.setListSciStudioImg(imgs);


        String orgArea = sciStudioDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            sciStudioDto.setOrgAreas(array);
        } else {
            String[] array = {};
            sciStudioDto.setOrgAreas(array);
        }
        String type = sciStudioDto.getType();
        if (type != null && type.contains(";")) {
            String[] array = type.split(";");
            sciStudioDto.setTypes(array);
        } else {
            String[] array = {};
            sciStudioDto.setTypes(array);
        }

        if (sciStudioDto.getModelId() != null) {
            //TODO 把劳模信息也返回
            Optional<SciPersonnelInfo> ops2 = sciPersonnelInfoRepository.findById(sciStudioDto.getModelId());
            if (ops2.isPresent()) {
                //劳模信息
                SciPersonnelInfo sciPersonnelInfo = ops2.get();
                SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(sciPersonnelInfo);
                String matype = sciPersonnelInfoDto.getMatype();
                if (matype != null && matype.contains(";")) {
                    String[] array = matype.split(";");
                    sciPersonnelInfoDto.setMatypes(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setMatypes(array);
                }
                String retype = sciPersonnelInfoDto.getRetype();
                if (retype != null && retype.contains(";")) {
                    String[] array = retype.split(";");
                    sciPersonnelInfoDto.setRetypes(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setRetypes(array);
                }
                String keyword = sciPersonnelInfoDto.getKeyword();
                if (keyword != null && keyword.contains(";")) {
                    String[] array = keyword.split(";");
                    sciPersonnelInfoDto.setKeywords(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setKeywords(array);
                }
                String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                if (orgArea2 != null && orgArea2.contains(";")) {
                    String[] array = orgArea2.split(";");
                    sciPersonnelInfoDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    sciPersonnelInfoDto.setOrgAreas(array);
                }
                Integer myid = sciPersonnelInfoDto.getId();
                List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(myid);
                sciPersonnelInfoDto.setListResult(results);
                List<SciPersonnelInfoLesson> list4 = sciPersonnelInfoLessonRepository.findBySpId(myid);
                sciPersonnelInfoDto.setListLesson(list4);
                List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(myid);
                sciPersonnelInfoDto.setListWe(list3);
                List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(myid, model);
                sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs2);
                sciStudioDto.setSciPersonnelInfoDto(sciPersonnelInfoDto);
            }
        }

        return sciStudioDto;
    }

    public List<DictDetailDto> getStudioType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("studio_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(SciStudioEditDto dto) {
        SciStudio sciStudio = sciStudioRepository.findById(dto.getId()).orElseGet(SciStudio::new);
        //TODO 如果编辑时为驳回状态则 调整为区县待审核
        if (sciStudio.getAuditStatus().equals(bh)) {
            sciStudio.setAuditStatus(qxdsh);
        }
        ValidationUtil.isNull(sciStudio.getId(), "SciStudio", "id", dto.getId());

        sciStudio.setPic(dto.getPic());
        String name = dto.getName();
        if (name == null) {
            throw new BadRequestException("成果名称为空");
        }

        if (dto.getModelId() != null) {
            Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(dto.getModelId());
            if (!ops.isPresent()) {
                throw new BadRequestException("未找到劳模");
            }
        }


        sciStudio.setModelId(dto.getModelId());
        sciStudio.setName(name);
        sciStudio.setUnit(dto.getUnit());
        sciStudio.setSzUnit(dto.getSzUnit());
        sciStudio.setNum(dto.getNum());
        sciStudio.setStudioCreateYear(dto.getStudioCreateYear());
        sciStudio.setMainWork(dto.getMainWork());
        sciStudio.setContacts(dto.getContacts());
        sciStudio.setContactsWay(dto.getContactsWay());
        sciStudio.setLeaderName(dto.getLeaderName());
        sciStudio.setLeaderSex(dto.getLeaderSex());
        sciStudio.setLeaderBirth(dto.getLeaderBirth());
        sciStudio.setLeaderPostUnit(dto.getLeaderPostUnit());
        sciStudio.setLeaderHonor(dto.getLeaderHonor());
        sciStudio.setLeaderAwardYear(dto.getLeaderAwardYear());
        sciStudio.setDetails(dto.getDetails());
        sciStudio.setBndYearExpenses(dto.getBndYearExpenses());
        sciStudio.setSYearInCons(dto.getSYearInCons());
        sciStudio.setSCxResult(dto.getSCxResult());
        sciStudio.setSCxResultChange(dto.getSCxResultChange());
        sciStudio.setSCxZlApplyCons(dto.getSCxZlApplyCons());
        sciStudio.setSRcTrain(dto.getSRcTrain());
        sciStudio.setSRcSkillLevel(dto.getSRcSkillLevel());
        sciStudio.setPic(dto.getPic());
        sciStudio.setSJjCsFee(dto.getSJjCsFee());
        sciStudio.setSJjJyFee(dto.getSJjJyFee());
        sciStudio.setSShxy(dto.getSShxy());
        sciStudio.setIsDelete(dto.getIsDelete());
        sciStudio.setIsShow(dto.getIsShow());
        sciStudio.setSort(dto.getSort());
        if (dto.getTypes() != null && dto.getTypes().length > 0) {
            String last = "";
            for (String a : dto.getTypes()) {
                last = last + a + ";";
            }
            sciStudio.setType(last);
        } else {
            sciStudio.setType(null);
        }
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            sciStudio.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            sciStudio.setOrgArea(orgAreaReturn());
        }
        SciStudio save = sciStudioRepository.save(sciStudio);

        List<String> listSciStudioImg = dto.getListSciStudioImg();
        if (listSciStudioImg != null && listSciStudioImg.size() > 0) {
            List<SciStudioImg> all2 = sciStudioImgRepository.findByStId(save.getId());
            if (all2 != null && all2.size() > 0) {
                for (SciStudioImg result : all2) {
                    sciStudioImgRepository.deleteById(result.getId());
                }
            }
            for (String res : listSciStudioImg) {
                SciStudioImg sciStudioImg = new SciStudioImg();
                sciStudioImg.setPic(res);
                sciStudioImg.setStId(save.getId());
                sciStudioImgRepository.save(sciStudioImg);
            }
        }
        List<SciStudioInfoAddDto> listSciStudioInfo = dto.getListSciStudioInfo();
        if (listSciStudioInfo != null && listSciStudioInfo.size() > 0) {
            List<SciStudioInfo> all3 = sciStudioInfoRepository.findByStId(save.getId());
            if (all3 != null && all3.size() > 0) {
                for (SciStudioInfo result : all3) {
                    sciStudioInfoRepository.deleteById(result.getId());
                }
            }
            for (SciStudioInfoAddDto res : listSciStudioInfo) {
                SciStudioInfo sciStudioInfo = new SciStudioInfo();
                sciStudioInfo.setName(res.getName());
                sciStudioInfo.setWork(res.getWork());
                sciStudioInfo.setTitle(res.getTitle());
                sciStudioInfo.setUnitPosition(res.getUnitPosition());
                sciStudioInfo.setStId(save.getId());
                sciStudioInfoRepository.save(sciStudioInfo);
            }
        }
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //sciStudioRepository.deleteById(id);
            //假删除
            Optional<SciStudio> res = sciStudioRepository.findById(id);
            if (res.isPresent()) {
                SciStudio sciStudio = res.get();
                sciStudio.setIsDelete(1);
                Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
                sciStudio.setDeleteTime(currentTimestamp);
                sciStudioRepository.save(sciStudio);
            }
        }
    }

    public void download(List<SciStudioDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SciStudioDto sciStudio : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("工作室名称", sciStudio.getName());
            map.put("申报单位", sciStudio.getUnit());
            map.put("所在单位", sciStudio.getSzUnit());
            map.put("当前成员人数", sciStudio.getNum());
            map.put("工作室创建年份", sciStudio.getStudioCreateYear());
            map.put("工作室类型", sciStudio.getType());
            map.put("主要从事工作", sciStudio.getMainWork());
            map.put("申报联系人", sciStudio.getContacts());
            map.put("申报联系人联系方式", sciStudio.getContactsWay());
            map.put("领衔人姓名", sciStudio.getLeaderName());
            map.put("领衔人性别", sciStudio.getLeaderSex());
            map.put("领衔人出生年月", sciStudio.getLeaderBirth());
            map.put("领衔人单位及职务", sciStudio.getLeaderPostUnit());
            map.put("领衔人最高荣誉", sciStudio.getLeaderHonor());
            map.put("领衔人获奖年份", sciStudio.getLeaderAwardYear());
            map.put("简介", sciStudio.getDetails());
            map.put("本年度经费预算", sciStudio.getBndYearExpenses());
            map.put("上年度经费投入情况", sciStudio.getSYearInCons());
            map.put("上一年度创新成果项", sciStudio.getSCxResult());
            map.put("上一年度成果转化", sciStudio.getSCxResultChange());
            map.put("上一年度专利申请情况", sciStudio.getSCxZlApplyCons());
            map.put("上一年度培训人才", sciStudio.getSRcTrain());
            map.put("上一年度技能等级提升", sciStudio.getSRcSkillLevel());
            map.put("上一年度创收金额", sciStudio.getSJjCsFee());
            map.put("上一年度节约金额", sciStudio.getSJjJyFee());
            map.put("上一年度社会效益", sciStudio.getSShxy());
            map.put("工作室图片", sciStudio.getPic());
            map.put("是否删除 默认否", sciStudio.getIsDelete());
            map.put("区审核状态 默认未审核  zqx_audit_status", sciStudio.getAuditStatus());
            map.put("是否小程序展示", sciStudio.getIsShow());
            map.put("排序", sciStudio.getSort());
            map.put("填报用户", sciStudio.getUserId());
            map.put("热度", sciStudio.getHot());
            map.put("是否允许编辑默认否", sciStudio.getIsEdit());
            String orgArea = sciStudio.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Transactional(rollbackFor = Exception.class)
    public void isAllowEdit(AllowSciStudioDto dto) {
        Optional<SciStudio> res = sciStudioRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到工作室");
        }
        Integer isEdit = dto.getIsEdit();
        if (isEdit == null) {
            throw new BadRequestException("缺少参数");
        }
        if (isEdit != 0 && isEdit != 1) {
            throw new BadRequestException("参数错误无法操作");
        }
        SciStudio sciStudio = res.get();
        sciStudio.setIsEdit(isEdit);
        sciStudioRepository.save(sciStudio);
    }

    @Transactional(rollbackFor = Exception.class)
    public void auditSciStudio(AuditSciStudioDto dto) {
        Optional<SciStudio> res = sciStudioRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到工作室id");
        }
        String cAuditStatus = dto.getAuditStatus();
        if (cAuditStatus == null || cAuditStatus.equals("")) {
            throw new BadRequestException("缺少审核状态");
        }
        SciStudio sciStudio = res.get();
        //TODO 根据登录用户如果是市 的则审核市的字段    如果是区的则审核区的字段  admin暂不处理
        Long userId = SecurityUtils.getCurrentUserId();
        Optional<User> resUser = userRepository.findById(userId);
        if (!resUser.isPresent()) {
            throw new BadRequestException("未找到登录用户");
        }
        User user = resUser.get();
        String orgArea = user.getOrgArea();
        //TODO 如果orgArea里面有2个 ; 表示市级审核   3个; 表示区级审核  其他则不与通过
        if (orgArea == null || orgArea.equals("")) {
            throw new BadRequestException("缺少地区区域无法审核");
        }
        if (!orgArea.contains(";")) {
            throw new BadRequestException("地区区域不符合规范无法审核");
        }
        String[] results = orgArea.split(";");
        if (results.length == 1) {
            throw new BadRequestException("省级账号无法审核");
        } else if (results.length == 2) {
            if (cAuditStatus.equals(bh)) {//驳回
                if (!sciStudio.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //市级审核驳回 就变成区级待审核
                sciStudio.setAuditStatus(qxdsh);
                sciStudio.setIsEdit(1);//驳回设置为可编辑
                SciStudio save = sciStudioRepository.save(sciStudio);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核驳回建议
                modelDemandAuditLog.setType(gzs);
                modelDemandAuditLog.setStage(cityNoPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                if (!sciStudio.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //区级审核通过 市级审核通过则通过
                sciStudio.setAuditStatus(shtg);
                if (sciStudio.getIsEdit() == 1) {

                } else {
                    sciStudio.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                //审核通过设为显示
                sciStudio.setIsShow(1);
                SciStudio save = sciStudioRepository.save(sciStudio);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(gzs);
                modelDemandAuditLog.setStage(cityPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else if (results.length == 3) {
            if (cAuditStatus.equals(bh)) {//驳回
                //区级审核
                sciStudio.setIsEdit(1);//驳回设置为可编辑
                sciStudio.setAuditStatus(cAuditStatus);
                SciStudio save = sciStudioRepository.save(sciStudio);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(gzs);
                modelDemandAuditLog.setStage(quNoPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                //区级审核通过 变为市级待审核
                sciStudio.setAuditStatus(sjdsh);
                if (sciStudio.getIsEdit() == 1) {

                } else {
                    sciStudio.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                SciStudio save = sciStudioRepository.save(sciStudio);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(gzs);
                modelDemandAuditLog.setStage(quPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else {
            throw new BadRequestException("未符合的审级权限无法审核");
        }
    }
}